import React, { Component, useState, useEffect } from 'react';

class adFooter extends Component {
  render() {
    return (
      <div>
        尾部广告
        {/* <WatchCount></WatchCount> */}
        <br />
        <DelayedCount></DelayedCount>
      </div>
    );
  }
}

function WatchCount() {
  const [count, setCount] = useState(0);
  useEffect(
    function () {
      const id = setInterval(function log() {
        //过时的闭包   加入【】依赖
        console.log(`Count is: ${count}`);
      }, 1000);
      return function () {
        clearInterval(id);
      };
    },
    [count],
  );

  return (
    <div>
      {count}
      <button onClick={() => setCount(count + 1)}> 加1 </button>
    </div>
  );
}

function DelayedCount() {
  const [count, setCount] = useState(0);

  function handleClickAsync() {
    setTimeout(function delay() {
      setCount(count + 1);
      // 过时闭包   写成下面拿到最新值
      // setCount((count) => count + 1);
    }, 1000);
  }

  function handleClickSync() {
    setCount(count + 1);
    console.log(`Count is: ${count}`);
  }

  return (
    <div>
      {count}
      <button onClick={handleClickAsync}>Increase async</button>
      <button onClick={handleClickSync}>Increase sync</button>
    </div>
  );
}
/* 解决闭包的有效方法
正确设置 React Hook 的依赖项
对于过时的状态，使用函数方式更新状态 */

export default adFooter;
